package com.atguigu.msm.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msm.service.MsmService;
import com.atguigu.msm.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {
    //redis-cli.exe -h 127.0.0.1 -p 6379

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //通过阿里云发送验证码短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //首先从redis中取，如果获取到直接返回 否则发送
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //调用service发送手机验证码  验证码由程序生成
        //随机生成六位随机数
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        //调用service中发送短信的方法
        boolean flag = msmService.send(param, phone);
        if(flag){
            //发送成功 将验证码放入redis 设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);    //设置五分钟有效时长
            return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }

    }
}
